package pers.wk.queues.direct;

import com.rabbitmq.client.*;
import pers.wk.config.MQConfig;
import pers.wk.utils.MQConnectionUtils;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.concurrent.TimeoutException;

/**
 * 路由模式-短信消费者
 */
public class DirectSmsConsumer {

    public static void main(String[] args) throws IOException, TimeoutException {
        //1.ConnectionFactory
        ConnectionFactory connectionFactory = MQConnectionUtils.getConnectionFactory("/");
        Connection connection = null;
        Channel channel = null;
        try {
            //2.创建连接
            connection = connectionFactory.newConnection();
            //3.通过连接获取通道Channel
            channel = connection.createChannel();
            //创建交换机
            channel.exchangeDeclare(MQConfig.ExchangeName.DIRECT_EXCHANGE, MQConfig.ExchangeType.direct);
            //创建队列
            channel.queueDeclare(MQConfig.QueueNames.SMS_QUEUE,
                    false, false, false, null);
            String routingKey = "sms";
            channel.queueBind(MQConfig.QueueNames.SMS_QUEUE, MQConfig.ExchangeName.DIRECT_EXCHANGE, routingKey);
            System.out.println("路由模式-短信消费者启动。。。");

            Channel channelTemp = channel;
            channelTemp.basicConsume(MQConfig.QueueNames.SMS_QUEUE, false, (consumerTag, message) -> {
                //@FunctionalInterface DeliverCallback
                System.out.println(MessageFormat.format("短信消费者获取消息：【{1}】{0}",
                        new String(message.getBody(), "UTF-8")
                        , message.getEnvelope().getDeliveryTag()));
                //手动应答
                channelTemp.basicAck(message.getEnvelope().getDeliveryTag(), false);
            }, (consumerTag) -> {
                //@FunctionalInterface CancelCallback
            });

            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MQConnectionUtils.close(connection, channel);
        }
    }
}
